package com.yxh.lib_base.ext.viewbinding.ext

import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
import com.yxh.lib_base.util.LogUtils


fun Lifecycle.addObserver(
    create: (() -> Unit)? = null,
    resumed: (() -> Unit)? = null,
    destroyed: (() -> Unit)? = null
) {
    addObserver(LifecycleObserver(this, create, resumed, destroyed))
}


fun Lifecycle.addObserverDestroyed(destroyed: () -> Unit) {
    addObserver(LifecycleObserver(this, destroyed = destroyed))
}


class LifecycleObserver(
    var lifecycle: Lifecycle?,
    val create: (() -> Unit)? = null,
    val resumed: (() -> Unit)? = null,
    val destroyed: (() -> Unit)? = null
) : LifecycleEventObserver {
    override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
        LogUtils.e(
            "LifecycleObserver", "name:${source::class.java.simpleName} event：${event.targetState}"
        )
        when (source.lifecycle.currentState) {
            Lifecycle.State.DESTROYED -> {
                destroyed?.invoke()
                lifecycle?.apply {
                    removeObserver(this@LifecycleObserver)
                    lifecycle = null
                }
            }
            Lifecycle.State.CREATED -> {
                create?.invoke()
            }
            Lifecycle.State.RESUMED -> {
                resumed?.invoke()
            }
            else -> {
                LogUtils.e("LifecycleObserver", "功能尚未实现：")
            }
        }
    }

}